<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>MQTT客户端</title>
<!--    <script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.1.0/paho-mqtt.min.js"></script>-->
    <script src="./paho-mqtt.min.js"></script>
  <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }
        .container {
            display: flex;
            flex-direction: column;
            gap: 10px;
        }
        button {
            padding: 8px 16px;
            cursor: pointer;
            margin: 5px 0;
        }
        textarea, input {
            width: 100%;
            padding: 8px;
            box-sizing: border-box;
            margin: 5px 0;
        }
        #messages {
            border: 1px solid #ddd;
            padding: 10px;
            height: 300px;
            overflow-y: auto;
        }
        .status {
            padding: 10px;
            margin: 10px 0;
            border-radius: 4px;
            text-align: center;
        }
        .connected {
            background-color: #d4edda;
        }
        .disconnected {
            background-color: #f8d7da;
        }
        .message {
            margin: 5px 0;
            padding: 5px;
            border-bottom: 1px solid #eee;
        }
    </style>
</head>
<body>
<div class="container">
    <h1>MQTT客户端</h1>

    <div>
        <label for="server">服务器地址:</label>
        <input type="text" id="server" value="127.0.0.1">
    </div>

    <div>
        <label for="port">端口:</label>
        <input type="text" id="port" value="8083">
    </div>

    <div>
        <label for="clientId">客户端ID:</label>
        <input type="text" id="clientId" value="clientId-front"/>
    </div>

    <div id="status" class="status disconnected">未连接</div>

    <div>
        <button id="connectBtn" onclick="connect()">连接</button>
        <button id="disconnectBtn" onclick="disconnect()" disabled>断开连接</button>
    </div>

    <hr>

    <div>
        <label for="topic">主题:</label>
        <input type="text" id="topic" value="test/topic">
    </div>

    <div>
        <label for="message">消息:</label>
        <textarea id="message" rows="3"></textarea>
    </div>

    <div>
        <button id="publishBtn" onclick="publish()" disabled>发布消息</button>
        <button id="subscribeBtn" onclick="subscribe()" disabled>订阅主题</button>
        <button id="unsubscribeBtn" onclick="unsubscribe()" disabled>取消订阅</button>
    </div>

    <h3>消息日志:</h3>
    <div id="messages"></div>
</div>

<script>
    let client;
    let isConnected = false;
    let subscribedTopic = "";

    // 添加消息到日志
    function addMessage(type, content) {
        const messagesEl = document.getElementById('messages');
        const messageEl = document.createElement('div');
        messageEl.className = 'message';
        messageEl.innerHTML = `<strong>${type}:</strong> ${content}`;
        messagesEl.appendChild(messageEl);
        messagesEl.scrollTop = messagesEl.scrollHeight;
    }

    // 更新连接状态
    function updateStatus(connected, message) {
        isConnected = connected;
        const statusEl = document.getElementById('status');
        statusEl.textContent = message;
        statusEl.className = `status ${connected ? 'connected' : 'disconnected'}`;

        // 更新按钮状态
        document.getElementById('connectBtn').disabled = connected;
        document.getElementById('disconnectBtn').disabled = !connected;
        document.getElementById('publishBtn').disabled = !connected;
        document.getElementById('subscribeBtn').disabled = !connected;
        document.getElementById('unsubscribeBtn').disabled = !connected || !subscribedTopic;
    }

    // 连接MQTT服务器
    function connect() {
        const server = document.getElementById('server').value;
        const port = parseInt(document.getElementById('port').value);
        const clientId = document.getElementById('clientId').value;

        // 创建客户端实例
        client = new Paho.Client(
            server,
            port,
            '/mqtt',
            clientId
        );

        // 设置回调
        client.onConnectionLost = onConnectionLost;
        client.onMessageArrived = onMessageArrived;

        // 连接选项
        const options = {
            timeout: 10,
            useSSL: port === 8883 || port === 8084,
            onSuccess: onConnectSuccess,
            onFailure: onConnectFailure,
            reconnect: true
        };

        updateStatus(false, "正在连接...");
        addMessage("系统", `尝试连接到 ${server}:${port}`);

        // 开始连接
        client.connect(options);
    }

    // 连接成功回调
    function onConnectSuccess() {
        updateStatus(true, "已连接");
        addMessage("系统", "连接成功");
    }

    // 连接失败回调
    function onConnectFailure(error) {
        updateStatus(false, `连接失败: ${error.errorMessage}`);
        addMessage("系统", `连接失败: ${error.errorMessage}`);

        // 5秒后自动重试
        setTimeout(connect, 5000);
    }

    // 连接断开回调
    function onConnectionLost(response) {
        if (response.errorCode !== 0) {
            updateStatus(false, `连接断开: ${response.errorMessage}`);
            addMessage("系统", `连接断开: ${response.errorMessage}`);
        }
    }

    // 收到消息回调
    function onMessageArrived(message) {
        addMessage(`收到 [${message.destinationName}]`, message.payloadString);
    }

    // 断开连接
    function disconnect() {
        if (client && isConnected) {
            client.disconnect();
            updateStatus(false, "已断开连接");
            addMessage("系统", "已断开连接");
            subscribedTopic = "";
        }
    }

    // 发布消息
    function publish() {
        if (!isConnected) return;

        const topic = document.getElementById('topic').value;
        const message = document.getElementById('message').value;

        if (!topic || !message) {
            addMessage("系统", "主题和消息不能为空");
            return;
        }

        const mqttMessage = new Paho.Message(message);
        mqttMessage.destinationName = topic;
        mqttMessage.qos = 1;

        client.send(mqttMessage);
        addMessage(`发布到 [${topic}]`, message);
    }

    // 订阅主题
    function subscribe() {
        if (!isConnected) return;

        const topic = document.getElementById('topic').value;
        if (!topic) {
            addMessage("系统", "请输入订阅主题");
            return;
        }

        client.subscribe(topic, { qos: 1 });
        subscribedTopic = topic;
        document.getElementById('unsubscribeBtn').disabled = false;
        addMessage("系统", `已订阅主题: ${topic}`);
    }

    // 取消订阅
    function unsubscribe() {
        if (!isConnected || !subscribedTopic) return;

        client.unsubscribe(subscribedTopic);
        addMessage("系统", `已取消订阅: ${subscribedTopic}`);
        subscribedTopic = "";
        document.getElementById('unsubscribeBtn').disabled = true;
    }
</script>
</body>
</html>